package UnitTest;

/**
 * @Auther: Administrator
 * @Date: 2019/8/24/024 20 05
 * @Description:
 */

import java.util.HashMap;
import java.util.Map;

public class Binary {
    public static void main(String args[]) {
        System.out.println(cal(1, 2, -1));
    }


    public static int cal(int a, int b, int character) {
        if (character == 1) {
            return myMuti(a, b);
        } else if (character == 0) {
            return myDiv(a, b);
        } else if (character == -1) {
            return mySub(a,b);
        } else {
            System.exit(-1);
        }
        return 0;
    }

    public static int myAdd(int a, int b) {
        int sum;
        int carry;
        do {
            sum = a ^ b;
            carry = (a & b) << 1;
            a = sum;
            b = carry;
        } while (carry != 0);
        return sum;
    }

    public static int mySub(int a, int b) {
        return myAdd(a, myAdd(~b, 1));
    }

    public static int myMuti(int a, int b) {
        boolean flag = (b < 0);
        if (flag) b = -b;
        Map<Integer, Integer> map = new HashMap<Integer, Integer>();
        for (int i = 0; i < 32; i++) {
            map.put(1 << i, i);
        }
        int sum = 0;
        while (b > 0) {
            int last = b & (~b + 1);
            int count = map.get(last);
            sum += a << count;
            b = b & (b - 1);
        }
        if (flag) sum = -sum;
        return sum;
    }

    public static int myDiv(int a, int b) {
        boolean flag = (a < 0) ^ (b < 0);
        if (a < 0) a = -a;
        if (b < 0) b = -b;
        if (a < b) return 0;
        int msb = 0;
        while ((b << msb) < a) {
            msb++;
        }
        int q = 0;
        for (int i = msb; i >= 0; i--) {
            if ((b << i) > a) continue;
            q |= (1 << i);
            a -= (b << i);
        }
        if (flag) return -q;
        return q;
    }
}
